package com.hyg.lib_music.ui.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_music.R;
import com.hyg.lib_music.service.MusicService;
import com.hyg.lib_music.util.Ble.BLEUtils;
import com.hyg.lib_music.util.Ble.callback.OnReceiverCallback;

import java.util.Timer;
import java.util.TimerTask;



public class MusicSleepTestActivity extends BaseActivity implements View.OnClickListener{
    private static final String TAG = "MusicSleepTestActivity";
    private MusicService.MusicServiceBinder serviceBinder;
    private ProgressBar progressBar;
    private TextView txtProgress;
    private TextView musicTitleView;
    private TextView tx_wakeup;
    private Button btnWakeup;
    private ImageView btnPlayPre;
    private ImageView btnPlayNext;
    private ImageView btnPlayOrPause;
    private View progressArea;
    private View progressAreaOk;
    private int stopSecond = 36;//00;//倒计时默认一小时
    private Timer mTimer = null;
    private BLEUtils mBleUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_bluetooth_test);
        //设置紫色状态栏
//        this.setStatusBarColor(R.color.musicPrimary);
//        this.setDark(false);
//        this.setStatusBar();
        this.hideStatusNavigationBar();
        StatusBarUtil.setStatusBar(1,this,getResources().getColor(R.color.musicPrimary),60,null,null,false);

        init();

        //获得实例
        mBleUtils = BLEUtils.getInstance();

        // TODO 接收数据的监听
        mBleUtils.RegistReciveListener(TAG, new OnReceiverCallback() {
            @Override
            public void onReceiver(byte[] value) {
//                tvMsg.setText(HexUtil.bytesToHexString(value));
            }
        });
    }

    private void init() {
        progressBar = this.findViewById(R.id.progressBar);
        txtProgress = this.findViewById(R.id.txtProgress);
        progressArea = this.findViewById(R.id.progressArea);
        progressAreaOk = this.findViewById(R.id.progressAreaOk);
        tx_wakeup = this.findViewById(R.id.tx_wakeup);
        musicTitleView = this.findViewById(R.id.musicTitleView);
        btnWakeup = this.findViewById(R.id.bt_wakeup);
        btnPlayPre = this.findViewById(R.id.play_pre);
        btnPlayNext = this.findViewById(R.id.play_next);
        btnPlayOrPause = this.findViewById(R.id.play_or_pause);

        btnPlayOrPause.setOnClickListener(this);
        btnPlayPre.setOnClickListener(this);
        btnPlayNext.setOnClickListener(this);
        btnWakeup.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 起床

                //移除接收数据的监听
                mBleUtils.UnregistReciveListener(TAG);
                finish();
                Intent it = new Intent(MusicSleepTestActivity.this, MusicSleepResultActivity.class);
                MusicSleepTestActivity.this.startActivity(it);
                return false;
            }
        });

        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }

    private void hideStatusNavigationBar(){
        // 全屏展示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // 全屏显示，隐藏状态栏和导航栏，拉出状态栏和导航栏显示一会儿后消失。
                this.getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            } else {
                // 全屏显示，隐藏状态栏
                this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            }
        }
    }

    //定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;

            //注册监听器
            serviceBinder.registerOnStateChangeListener(listenr);

            //获得当前音乐
            Music item = serviceBinder.getCurrentMusic();

            if(item == null) {
            }
            else if (serviceBinder.isPlaying()){
                //如果正在播放音乐, 更新信息
                musicTitleView.setText(item.musicName);
                btnPlayOrPause.setImageResource(R.mipmap.ic_music_test_pause);

            }
            else {
                //当前有可播放音乐但没有播放
                musicTitleView.setText(item.musicName);
                btnPlayOrPause.setImageResource(R.mipmap.ic_music_test_play);

            }
            startTimer();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //断开连接之后, 注销监听器
            serviceBinder.unregisterOnStateChangeListener(listenr);
        }
    };

    //实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {

        @Override
        public void onPlayProgressChange(long played, long duration) {
        }

        @Override
        public void onPlay(final Music item) {
            //变为播放状态时
            musicTitleView.setText(item.musicName);
            btnPlayOrPause.setImageResource(R.mipmap.ic_music_test_pause);
        }

        @Override
        public void onPause() {
            //变为暂停状态时
            btnPlayOrPause.setImageResource(R.mipmap.ic_music_test_play);
        }
    };

    // 控件监听
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.play_pre) {// 上一首
            serviceBinder.playPre();
        } else if (id == R.id.play_next) {// 下一首
            serviceBinder.playNext();
        } else if (id == R.id.play_or_pause) {// 播放或暂停
            serviceBinder.playOrPause();
        }
    }

    /**
     * 返回时分秒
     * @param totalSeconds
     * @return
     */
    private String secondToTime(long totalSeconds) {

        if (totalSeconds < 1) {
            return "00:00:00";
        }
        //将秒格式化成HH:mm:ss
        //这里应该用Duration更合理，但它不能格式化成字符串
        //而使用LocalTime，在时间超过24小时后格式化也会有问题（！）
        int hours = (int) (totalSeconds / 3600);

        int rem = (int) (totalSeconds % 3600);
        int minutes = rem / 60;
        int seconds = rem % 60;

        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    //开始倒计时
    private void startTimer() {

        serviceBinder.stopMusicAlarm(stopSecond);
        if (mTimer == null) {
            mTimer = new Timer(true);
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                long limit = serviceBinder.getMusicAlarmLimit();
                Log.e("llllllllllllllll：", String.valueOf(limit/1000));
                if (0 == limit/1000) {

                    MusicSleepTestActivity.this.runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                            tx_wakeup.setVisibility(View.VISIBLE);
                            progressArea.setVisibility(View.GONE);
                            progressAreaOk.setVisibility(View.VISIBLE);
                            txtProgress.setText("00:00:00");

                        }
                    });
                    stopTimer();
                    return;
                }

                MusicSleepTestActivity.this.runOnUiThread(new Runnable()
                {
                    public void run()
                    {
                        long limit = serviceBinder.getMusicAlarmLimit();
                        String limitText = secondToTime(limit/1000);
                        txtProgress.setText(limitText);
                        progressBar.setProgress(100-(int) (limit/10/stopSecond));
                    }

                });

            }
        }, 0, 100);
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
        Log.e("llllllllllllllll:","onDestroy");
        unbindService(mServiceConnection);
        //移除接收数据的监听
        mBleUtils.UnregistReciveListener(TAG);
        // TODO 断开连接
        mBleUtils.CloseBleConn();
    }

}

